import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login'
// import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import User from '@/views/User'
// import Search from '@/views/Search'
// import SearchResult from '@/views/Search/SearchResult.vue'
// import ArticleDetail from '@/views/ArticleDetail'
// import UserEdit from '@/views/User/UserEdit'
// import Chat from '@/views/Chat'
import { getToken } from '@/utils/token.js'
Vue.use(VueRouter)

// 路由懒加载：为了让第一个页面，加载的app.js小一点，打开网页快一点
// 思路：把组件对应js，分成若干个.js，路由切换到哪个页面，才去加载对应的js文件

// webpackChunName注释语法，给生成的js文件起名字
const routes = [
  {
    path: '/',
    redirect: '/layout/home' // 默认显示二级页面为home首页
  },
  {
    path: '/login',
    component: () => import(/* webpackChunkName: "Login" */ '@/views/Login'),
    // 路由独享守卫
    beforeEnter (to, from, next) {
      if (getToken()?.length > 0) {
        // next(false)// 留在原地 不改动
        // 问题：手动修改url路由路径，next(false)会给你跳转回首页，但这里又不让跳转
        // 所以产生一次历史记录，让返回按钮$router.back()失效 一直停留在本地
        next('/layout/home')
      } else {
        next()
      }
    }
  },
  {
    path: '/layout',
    component: () => import(/* webpackChunkName: "Layout" */ '@/views/Layout'),
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "Home" */ '@/views/Home'),
        meta: {
          scrollT: 0 // 保存首页离开时，滚动条位置
        }
      },
      {
        path: 'user',
        component: () => import(/* webpackChunkName: "User" */ '@/views/User')
      }

    ]
  },
  {
    path: '/search',
    component: () => import(/* webpackChunkName: "Search" */ '@/views/Search')
  },
  {
    path: '/search_result/:kw',
    component: () => import(/* webpackChunkName: "SearchResult" */ '@/views/Search/SearchResult.vue')
  },
  {
    path: '/detail',
    component: () => import(/* webpackChunkName: "ArticleDetail" */ '@/views/ArticleDetail')
  },
  {
    path: '/user_editor',
    component: () => import(/* webpackChunkName: "UserEdit" */ '@/views/User/UserEdit')
  },
  {
    path: '/chat',
    component: () => import(/* webpackChunkName: "Chat" */ '@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})

// // 路由 - 全局前置守卫（在路由发生真正跳转之前，执行此函数）
// // 此函数可以决定路由是否跳转/取消/强制中断切换到别的路由
// router.beforeEach((to, from, next) => {
//   // 如果已经登录了，不要切换到登录页面
//   if (getToken()?.length > 0 && to.path === '/login') {
//     next(false) // 留在原地 不改动
//   } else {
//     next() // 其他情况统统放行
//   }
// })
export default router
